<?
function check_rewrite($iNews,$rNews){
    $db_select      = new db_query('SELECT new_title 
                                    FROM news
                                    WHERE new_id = '.$iNews);
    $row = mysql_fetch_assoc($db_select->result);
    if($row){
        $arr_replace = array(':','?','.','"',"'",'','/');
        $rNews  = str_replace($arr_replace,'+',$rNews);
        $rwrite = str_replace($arr_replace,'+',$row['new_title']);
        $rNews  = str_replace(' ','+',$rNews);
        $rwrite = str_replace(' ','+',$rwrite);
        if($rNews!=$rwrite){
            redirect('/'.$iNews.'/'.$rwrite.'.htm');
        }
    }
}
function split_title($str){
    $arr_replace    = array('.',',','"',":");
    $str            = str_replace($arr_replace,'',$str);   
    $arr_string     = explode(' ',$str);
    $total          = count($arr_string);
    $arr_split      = array();
    for($i=0; $i<= $total; $i++){
        if($i<=$total - 3){
            //$arr_split[] = $arr_string[$i];
            $arr_split[] = $arr_string[$i].' '.$arr_string[$i+1];
            $arr_split[] = $arr_string[$i].' '.$arr_string[$i+1].' '.$arr_string[$i+2];
        }else if($i == $total - 2){
            //$arr_split[] = $arr_string[$i];
            $arr_split[] = $arr_string[$i].' '.$arr_string[$i+1];
        }
    }
    return $arr_split;
}
function GetNamecat($id){
   $db_cat  = new db_query('SELECT cat_name
                        FROM categories_multi
                        WHERE cat_id = '.$id.' AND cat_active = 1');
   while($row = mysql_fetch_assoc($db_cat->result)){
      return $row['cat_name'];
   }
}
function check_domain($domain,$url = ''){
   $arrCheck = parse_url($url);
   if(@$arrCheck['host'] !=''){
      return $url;
   }else{
      $db_query = new db_query('SELECT dom_name 
                                 FROM domain
                                 WHERE dom_id='.$domain);
      while($row = mysql_fetch_assoc($db_query->result)){
         $url = $row['dom_name'].$url;
         return $url;
      }   
   }
}
function base64_url_encode($input){
	return strtr(base64_encode($input), '+/=', '_,-');
}

function base64_url_decode($input) {
	return base64_decode(strtr($input, '_,-', '+/='));
}
function breakKey($content, $title, $tag=0){
	$title 			= mb_strtolower($title,"UTF-8");
	$array 			= explode(".",$content);
	$contentReturn = '';
	$arrayKey 		= explode(" ", $title);
	$arraySort 		= array();
	$arResult 		= array();
	foreach($array as $key=>$value){
		$value 				= mb_strtolower($value,"UTF-8");
		$arrayCau 			= explode(" ",$value);
		$result 	 			= array_intersect($arrayKey, $arrayCau);
		$arraySort[$key] 	= count($result);
		$arResult[$key]	= $result;
	}
	arsort($arraySort);
	$i=0;
	foreach($arraySort as $key=>$value){
		$i++;
		if(isset($array[$key]) && isset($arResult[$key])){
			$contentReturn = $contentReturn . replaceTag(cut_string($array[$key], 200), $arResult[$key]) . '. ';
		}
		if($i==3) break;
	}
	unset($result);
	unset($arraySort);
	unset($arResult);
	if($tag==1) $this->text .= strip_tags($contentReturn);
	$contentReturn = str_replace("</b>"," ",$contentReturn);
	
	return $contentReturn;
}
function count_word($str){
    $str = removeAccent(removeHTML($str));
    return str_word_count($str);
}
function down_picture($filename, $path = "../pictures/news/"){
	
	$db_select	=	new db_query("SELECT pic_source
											FROM pictures
											WHERE pic_name = '" . $filename . "'");
	if($row = mysql_fetch_assoc($db_select->result)){
		$filePath	= $path . $filename;
		$url	=	$row['pic_source'];
		$ch	=	curl_init($url);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");	
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		$result	=	curl_exec($ch);
		curl_close($ch);  
		$fp	=	fopen($filePath, 'w+');
		fwrite($fp, $result);
		fclose($fp);
		
		$db_ex	=	new db_execute("DELETE FROM pictures WHERE pic_name = '" . $filename . "'");
		unset($db_ex);
		
		return true;
	}
	unset($db_select);
	return false;
}

function array_currency(){
	$arrReturn	= array(0 => "USD", 1 => "EUR");
	return $arrReturn;
}
function array_language(){
	$db_language	= new db_query("SELECT * FROM languages ORDER BY lang_id ASC");
	$arrReturn		= array();
	while($row = mysql_fetch_array($db_language->result)){
		$arrReturn[$row["lang_id"]] = array($row["lang_code"], $row["lang_name"]);
	}
	return $arrReturn;
}

function callback($buffer){
	$str		= array(chr(9), chr(10));
	$buffer	= str_replace($str, "", $buffer);
	return $buffer;
}

function check_email_address($email) {
	//First, we check that there's one @ symbol, and that the lengths are right
	if(!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)){
		//Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
		return false;
	}
	//Split it into sections to make life easier
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);
	for($i = 0; $i < sizeof($local_array); $i++){
		if(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])){
			return false;
		}
	}
	if(!ereg("^\[?[0-9\.]+\]?$", $email_array[1])){
	//Check if domain is IP. If not, it should be valid domain name
		$domain_array = explode(".", $email_array[1]);
		if(sizeof($domain_array) < 2){
			return false; // Not enough parts to domain
		}
		for($i = 0; $i < sizeof($domain_array); $i++){
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])){
				return false;
			}
		}
	}
	return true;
}

function check_session_security($security_code){
	$return = 1;
	if(!isset($_SESSION["session_security_code"])) $_SESSION["session_security_code"] = generate_security_code();
	if($security_code != $_SESSION["session_security_code"]){
		$return = 0;
	}
	// Reset lại session security code
	$_SESSION["session_security_code"] = generate_security_code();
	return $return;
}

function count_online(){
	$visited_timeout		= 10 * 60;
	$last_visited_time	= time();
	//Kiem tra co session_id hay ko, neu co
	if(session_id() != ""){
		$db_exec	= new db_execute("REPLACE INTO active_users(au_session_id, au_last_visit) VALUES('" . session_id() . "', " . $last_visited_time . ")");
		unset($db_exec);
	}
	// Delete timeout
	$db_exec	= new db_execute("DELETE FROM active_users WHERE au_last_visit < " . ($last_visited_time - $visited_timeout));
	unset($db_exec);
	// Select Count
	$db_count= new db_query("SELECT count(*) AS count FROM active_users");
	$row		= mysql_fetch_array($db_count->result);
	unset($db_count);
	// Return value
	return $row["count"];
}

function count_visited(){
	$db_count	= new db_query("SELECT vis_counter FROM visited");
	$row = mysql_fetch_array($db_count->result);
	unset($db_count);
	return $row["vis_counter"];
}

function cut_string($str, $length, $char=" ..."){
	//Nếu chuỗi cần cắt nhỏ hơn $length thì return luôn
	$strlen	= mb_strlen($str, "UTF-8");
	if($strlen <= $length) return $str;
	
	//Cắt chiều dài chuỗi $str tới đoạn cần lấy
	$substr	= mb_substr($str, 0, $length, "UTF-8");
	if(mb_substr($str, $length, 1, "UTF-8") == " ") return $substr . $char;
	
	//Xác định dấu " " cuối cùng trong chuỗi $substr vừa cắt
	$strPoint= mb_strrpos($substr, " ", "UTF-8");
	
	//Return string
	if($strPoint < $length - 20) return $substr . $char;
	else return mb_substr($substr, 0, $strPoint, "UTF-8") . $char;
}
function fb_like($link,$layout='button_count',$width=90,$height=20){
    return '<iframe class="iframe_fbl" src="http://www.facebook.com/plugins/like.php?href='.$link.'&layout='.$layout.'&show_faces=true&width=90&action=like&colorscheme=light&height=20" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'.$width.'px; height:'.$height.'px;" allowTransparency="true"></iframe>';
}
function fb_share($link,$custom = 0){
    if($custom){
        return 'http://www.facebook.com/sharer/sharer.php?u='.$link;
    }else{
        return '<a href="http://www.facebook.com/sharer/sharer.php?u='.$link.'" target="_blank"><img src="/themes/img/sharefb.png"/></a>';    
    }
    
}
function format_number($number, $edit=0){
	if($edit == 0){
		$return	= number_format($number, 2, ".", ",");
		if(intval(substr($return, -2, 2)) == 0) $return = number_format($number, 0, ".", ",");
		elseif(intval(substr($return, -1, 1)) == 0) $return = number_format($number, 1, ".", ",");
		return $return;
	}
	else{
		$return	= number_format($number, 2, ".", "");
		if(intval(substr($return, -2, 2)) == 0) $return = number_format($number, 0, ".", "");
		return $return;
	}
}

function generate_array_variable($variable){
	$list			= tdt($variable);
	$arrTemp		= explode("{-break-}", $list);
	$arrReturn	= array();
	for($i=0; $i<count($arrTemp); $i++) $arrReturn[$i] = trim($arrTemp[$i]);
	return $arrReturn;
}

function generate_security_code(){
	$code	= rand(1000, 9999);
	return $code;
}
//Function lấy html của 1 url truyền vào
function getcontent($url, $post = "", $refer = "", $usecookie = false) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	
	if($post) {
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt ($curl, CURLOPT_POSTFIELDS, $post);
	}
	
	if($refer) {
		curl_setopt($curl, CURLOPT_REFERER,$refer);
	}
	
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3"); 
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	//curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);
	
	if ($usecookie) { 
		curl_setopt($curl, CURLOPT_COOKIEJAR, $usecookie); 
		curl_setopt($curl, CURLOPT_COOKIEFILE, $usecookie);    
	}
	
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); 
	
	$html = curl_exec($curl);
	curl_close($curl);
	return $html;
}
function getlinks($link, $root = ""){
	$link_return	=	$link;
	if(substr($link, 0, 4) != "http"){
		$link			=	str_replace("..", "", $link);
		$link_return =	$root . $link;
	}
	return $link_return;
}
// function generate_name($filename){
// 	$name = "";
// 	for($i=0; $i<3; $i++){
// 		$name .= chr(rand(97,122));
// 	}
// 	$today= getdate();
// 	$name.= $today[0];
// 	$ext	= substr($filename, (strrpos($filename, ".") + 1));
// 	return $name . "." . $ext;
// }
function get_image($url, $path){
	$filename	=	generate_name($url);
	
	$filePath	= $path . $filename;
	
	$ch	=	curl_init($url);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	$result	=	curl_exec($ch);
	curl_close($ch);  
	$fp	=	fopen($filePath,'w+');
	fwrite($fp, $result);
	fclose($fp);
	
	return $filename;
}
function get_image_news($new_id){
	$new_id	=	intval($new_id);
	$db_picture	=	new db_query("SELECT *
											FROM pictures
											WHERE pic_new_id = " . $new_id);
	while($row_pic = mysql_fetch_assoc($db_picture->result)){
		down_picture($row_pic['pic_source'], $row_pic['pic_name']);
	}
	unset($db_picture);
	$db_ex	=	new db_execute("UPDATE news SET new_down_image = 1 WHERE new_id = " . $new_id);
	unset($db_ex);
	$db_ex	=	new db_execute("DELETE FROM pictures WHERE pic_new_id = " . $new_id);
	unset($db_ex);
}


function getURL($serverName=0, $scriptName=0, $fileName=1, $queryString=1, $varDenied=''){
	$url	 = '';
	$slash = '/';
	if($scriptName != 0)$slash	= "";
	if($serverName != 0){
		if(isset($_SERVER['SERVER_NAME'])){
			$url .= 'http://' . $_SERVER['SERVER_NAME'];
			if(isset($_SERVER['SERVER_PORT'])) $url .= ":" . $_SERVER['SERVER_PORT'];
			$url .= $slash;
		}
	}
	if($scriptName != 0){
		if(isset($_SERVER['SCRIPT_NAME']))	$url .= substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/') + 1);
	}
	if($fileName	!= 0){
		if(isset($_SERVER['SCRIPT_NAME']))	$url .= substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], '/') + 1);
	}
	if($queryString!= 0){
		$url .= '?';
		reset($_GET);
		$i = 0;
		if($varDenied != ''){
			$arrVarDenied = explode('|', $varDenied);
			while(list($k, $v) = each($_GET)){
				if(array_search($k, $arrVarDenied) === false){
					$i++;
					if($i > 1) $url .= '&' . $k . '=' . @urlencode($v);
					else $url .= $k . '=' . @urlencode($v);
				}
			}
		}
		else{
			while(list($k, $v) = each($_GET)){
				$i++;
				if($i > 1) $url .= '&' . $k . '=' . @urlencode($v);
				else $url .= $k . '=' . @urlencode($v);
			}
		}
	}
	$url = str_replace('"', '&quot;', strval($url));
	return $url;
}
function generate_keyword($str = ""){
	$keyword			=	"";
	
	$arr_special	=	array("(", ")", ".", ",", "|", "'", "\"", "'", "-", "/", "_", "\\", "“", "”");
	$str				=	str_replace($arr_special, " ", $str);
	for($i = 1; $i <= 15; $i++){
		$str			=	str_replace("  ", " ", $str);
	}
	
	$str				=	trim($str);
	$str_kodau		=	removeAccent($str);
	
	$keyword			=	$str	. " " . $str_kodau;
	
	$keyword			=	str_replace(" ", ", ", $keyword);
	
	return  $keyword;
}
function getValue($value_name, $data_type = "int", $method = "GET", $default_value = 0, $advance = 0){
	$value = $default_value;
	switch($method){
		case "GET": if(isset($_GET[$value_name])) $value = $_GET[$value_name]; break;
		case "POST": if(isset($_POST[$value_name])) $value = $_POST[$value_name]; break;
		case "COOKIE": if(isset($_COOKIE[$value_name])) $value = $_COOKIE[$value_name]; break;
		case "SESSION": if(isset($_SESSION[$value_name])) $value = $_SESSION[$value_name]; break;
		default: if(isset($_GET[$value_name])) $value = $_GET[$value_name]; break;
	}
	$valueArray	= array("int" => intval($value), "str" => trim(strval($value)), "flo" => floatval($value), "dbl" => doubleval($value), "arr" => $value);
	foreach($valueArray as $key => $returnValue){
		if($data_type == $key){
			if($advance != 0){
				switch($advance){
					case 1:
						$returnValue = replaceMQ($returnValue);
						break;
					case 2:
						$returnValue = htmlspecialbo($returnValue);
						break;
				}
			}
			//Do số quá lớn nên phải kiểm tra trước khi trả về giá trị
			if((strval($returnValue) == "INF") && ($data_type != "str")) return 0;
			return $returnValue;
			break;
		}
	}
	return (intval($value));
}

function get_server_name(){
	$server = $_SERVER['SERVER_NAME'];
	if(strpos($server, "asiaqueentour.com") !== false) return "http://www.asiaqueentour.com";
	else return "http://" . $server . ":" . $_SERVER['SERVER_PORT'];
}

function htmlspecialbo($str){
	$arrDenied	= array('<', '>', '\"', '"');
	$arrReplace	= array('&lt;', '&gt;', '&quot;', '&quot;');
	$str = str_replace($arrDenied, $arrReplace, $str);
	return $str;
}

function javascript_writer($str){
	$mytextencode = "";
	for ($i=0;$i<strlen($str);$i++){
		$mytextencode .= ord(substr($str,$i,1)) . ",";
	}
	if ($mytextencode!="") $mytextencode .= "32";
	return "<script language='javascript'>document.write(String.fromCharCode(" . $mytextencode . "));</script>";
}

function lang_path(){
	global $lang_id;
	global $array_lang;
	global $con_root_path;
	$default_lang = 1;
	$path	= ($lang_id == $default_lang) ? $con_root_path : $con_root_path . $array_lang[$lang_id][0] . "/";
	return $path;
}

function microtime_float(){
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

function random(){
	$rand_value = "";
	$rand_value.= rand(1000,9999);
	$rand_value.= chr(rand(65,90));
	$rand_value.= rand(1000,9999);
	$rand_value.= chr(rand(97,122));
	$rand_value.= rand(1000,9999);
	$rand_value.= chr(rand(97,122));
	$rand_value.= rand(1000,9999);
	return $rand_value;
}

function redirect($url){
	$url	= htmlspecialbo($url);
	echo '<script type="text/javascript">window.location.href = "' . $url . '";</script>';
	exit();
}
function replaceTag($content,$array=array()){
		
	if(count($array)>0){
		foreach($array as $key=>$value){
			$value = trim($value);
			if($value!=''){
				//echo $value. chr(13);
				//$content = @preg_replace("#" . $value . "#Usi","<b>$0</b>",$content);
				//echo $content;
			}
		}
	}
	return $content;
}
function removeAccent($mystring){
	$vnarray = array(  
            'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ|&agrave;|&aacute;|&acirc;|&atilde;',  
            'd'=>'đ',  
            'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|&egrave;|&eacute;|&ecirc;|&etilde;',  
            'i'=>'í|ì|ỉ|ĩ|ị|&igrave;|&iacute;|&icirc;|&itilde;',  
            'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ|&ograve;|&oacute;|&ocirc;|&otilde;',  
            'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|&ugrave;|&uacute;|&ucirc;|&utilde;',  
            'y'=>'ý|ỳ|ỷ|ỹ|ỵ',  
            'A'=>'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ|&Agrave;|&Aacute;|&Acirc;|&Atilde;',  
            'D'=>'Đ',  
            'E'=>'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ|&Egrave;|&Eacute;|&Ecirc;|&Etilde;',  
            'I'=>'Í|Ì|Ỉ|Ĩ|Ị|&Igrave;|&Iacute;|&Icirc;|&Itilde;',  
            'O'=>'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|&Ograve;|&Oacute;|&Ocirc;|&Otilde;',  
            'U'=>'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự|&Ugrave;|&Uacute;|&Ucirc;|&Utilde;',  
            'Y'=>'Ý|Ỳ|Ỷ|Ỹ|Ỵ',  
        ); 
    foreach($vnarray as $en=>$uni){  
        $string = preg_replace("/($uni)/i", $en, $mystring);  
    }  
    return $mystring;  
}
function removeSign($str){
    $coDau=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
    "ằ","ắ","ặ","ẳ","ẵ",
    "è","é","ẹ","ẻ","ẽ","ê","ề" ,"ế","ệ","ể","ễ",
    "ì","í","ị","ỉ","ĩ",
    "ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
    ,"ờ","ớ","ợ","ở","ỡ",
    "ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
    "ỳ","ý","ỵ","ỷ","ỹ",
    "đ",
    "À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
    ,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
    "È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
    "Ì","Í","Ị","Ỉ","Ĩ",
    "Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
    ,"Ờ","Ớ","Ợ","Ở","Ỡ",
    "Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
    "Ỳ","Ý","Ỵ","Ỷ","Ỹ",
    "Đ","ê","ù","à");

    $khongDau=array("a","a","a","a","a","a","a","a","a","a","a"
    ,"a","a","a","a","a","a",
    "e","e","e","e","e","e","e","e","e","e","e",
    "i","i","i","i","i",
    "o","o","o","o","o","o","o","o","o","o","o","o"
    ,"o","o","o","o","o",
    "u","u","u","u","u","u","u","u","u","u","u",
    "y","y","y","y","y",
    "d",
    "A","A","A","A","A","A","A","A","A","A","A","A"
    ,"A","A","A","A","A",
    "E","E","E","E","E","E","E","E","E","E","E",
    "I","I","I","I","I",
    "O","O","O","O","O","O","O","O","O","O","O","O"
    ,"O","O","O","O","O",
    "U","U","U","U","U","U","U","U","U","U","U",
    "Y","Y","Y","Y","Y",
    "D","e","u","a");
    return str_replace($coDau,$khongDau,$str);
}
function removeHTML($string){
	$string = preg_replace ('/<script.*?\>.*?<\/script>/si', ' ', $string); 
	$string = preg_replace ('/<style.*?\>.*?<\/style>/si', ' ', $string); 
	$string = preg_replace ('/<.*?\>/si', ' ', $string); 
	$string = str_replace ('&nbsp;', ' ', $string);
	return $string;
}

function removeLink($string){
	$string = preg_replace ('/<a.*?\>/si', '', $string);
	$string = preg_replace ('/<\/a>/si', '', $string);
	return $string;
}

function removeScript($string){
	$string = preg_replace ('/<script.*?\>.*?<\/script>/si', '<br />', $string);
	$string = preg_replace ('/on([a-zA-Z]*)=".*?"/si', ' ', $string);
	$string = preg_replace ('/On([a-zA-Z]*)=".*?"/si', ' ', $string);
	$string = preg_replace ("/on([a-zA-Z]*)='.*?'/si", " ", $string);
	$string = preg_replace ("/On([a-zA-Z]*)='.*?'/si", " ", $string);
	return $string; 
}

function replaceFCK($string, $type=0){
	$array_fck	= array ("&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Igrave;", "&Iacute;", "&Icirc;",
								"&Iuml;", "&ETH;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ugrave;", "&Uacute;", "&Yacute;", "&agrave;",
								"&aacute;", "&acirc;", "&atilde;", "&egrave;", "&eacute;", "&ecirc;", "&igrave;", "&iacute;", "&ograve;", "&oacute;",
								"&ocirc;", "&otilde;", "&ugrave;", "&uacute;", "&ucirc;", "&yacute;",
								);
	$array_text	= array ("À", "Á", "Â", "Ã", "È", "É", "Ê", "Ì", "Í", "Î",
								"Ï", "Ð", "Ò", "Ó", "Ô", "Õ", "Ù", "Ú", "Ý", "à",
								"á", "â", "ã", "è", "é", "ê", "ì", "í", "ò", "ó",
								"ô", "õ", "ù", "ú", "û", "ý",
								);
	if($type == 1) $string = str_replace($array_fck, $array_text, $string);
	else $string = str_replace($array_text, $array_fck, $string);
	return $string;
}

function replaceJS($text){
	$arr_str = array("\'", "'", '"', "&#39", "&#39;", chr(10), chr(13), "\n");
	$arr_rep = array(" ", " ", '&quot;', " ", " ", " ", " ");
	$text		= str_replace($arr_str, $arr_rep, $text);
	$text		= str_replace("    ", " ", $text);
	$text		= str_replace("   ", " ", $text);
	$text		= str_replace("  ", " ", $text);
	return $text;
}

function replace_keyword_search($keyword, $lower=1){
	if($lower == 1) $keyword	= mb_strtolower($keyword, "UTF-8");
	$keyword	= replaceMQ($keyword);
	$arrRep	= array("'", '"', "-", "+", "=", "*", "?", "/", "!", "~", "#", "@", "%", "$", "^", "&", "(", ")", ";", ":", "\\", ".", ",", "[", "]", "{", "}", "‘", "’", '“', '”');
	$keyword	= str_replace($arrRep, " ", $keyword);
	$keyword	= str_replace("  ", " ", $keyword);
	$keyword	= str_replace("  ", " ", $keyword);
	return $keyword;
}

function replaceMQ($text){
	$text	= str_replace("\'", "'", $text);
	$text	= str_replace("'", "''", $text);
	return $text;
}

function remove_magic_quote($str){
	$str = str_replace("\'", "'", $str);
	$str = str_replace("\&quot;", "&quot;", $str);
	$str = str_replace("\\\\", "\\", $str);
	return $str;
}

function scoreColor($score){
    switch(1){
        case ($score <=5):
            return 'score05';
        break;
        case ($score >5 && $score <= 6):
            return 'score56';
        break;
        case ($score >6 && $score <= 7):
            return 'score67';
        break;
        case ($score >7 && $score <= 8):
            return 'score78';
        break;
        case ($score >8 && $score <= 9):
            return 'score89';
        break;
        case ($score >9 && $score <= 10):
            return 'score910';
        break;
    }
}

function tdt($variable){
	global $lang_display;
	if (isset($lang_display[$variable])){
		if (trim($lang_display[$variable]) == ""){
			return "#" . $variable . "#";
		}
		else{
			$arrStr	= array("\\\\'", '\"');
			$arrRep	= array("\\'", '"');
			return str_replace($arrStr, $arrRep, $lang_display[$variable]);
		}
	}
	else{
		return "_@" . $variable . "@_";
	}
}


function save_log_info($filename, $content){
	$break_line		=	"---------------------------------------------------------------------------";
	$log_path     =   $_SERVER["DOCUMENT_ROOT"] . "/ipstore/";
	$handle       =   @fopen($log_path . $filename . ".cfn", "a");
	//Neu handle chua co mo thêm ../
	if (!$handle) $handle = @fopen($log_path . $filename . ".cfn", "a");
	//Neu ko mo dc lan 2 thi exit luon
	if (!$handle) exit();		
	fwrite($handle, date("d/m/Y h:i:s A") . " " . @$_SERVER["REQUEST_URI"] . PHP_EOL . $content . PHP_EOL . PHP_EOL . $break_line . PHP_EOL . PHP_EOL);	
	fclose($handle);
}
//Hàm sắp xếp
function sort_desc_array_value($a, $b) {
    if ($a['sorting'] == $b['sorting']) {
        return 0;
    }
    return ($a['sorting'] > $b['sorting']) ? -1 : 1;
}
function sort_by_order_array_asc($a, $b){
    if ($a['order'] == $b['order']) {
        return 0;
    }
    return ($a['order'] < $b['order']) ? -1 : 1;
}
function TagToLinkSearch($str){
    $arrtag = explode(',',trim($str));
    $strtag = '';
    $arrtag = array_filter($arrtag);
    foreach($arrtag as $tag){
        $strtag .= '<a href="/tim-kiem/tin-tuc.html?q='.urlencode($tag).'" target="_blank"><span class="tag-word" itemprop="keywords">'.$tag.'</span></a>';
    }
    return $strtag;
}
function TagToLinkSearchSpider($str){
    $arrtag = explode(',',trim($str));
    $strtag = '';
    $arrtag = array_filter($arrtag);
    foreach($arrtag as $tag){
        $strtag .= '<a href="/spider-search.html?keyword='.urlencode($tag).'" target="_blank" class="tag-word">'.$tag.'</a>';
    }
    return $strtag;
}
function TagToLinkSearchTags($str){
    $arrtag = explode(',',$str);
    $strtag = '';
    $total_arr = count($arrtag);
    foreach($arrtag as $key=>$tag){
      if($tag != ''){
         $strtag .= '<a href="/tags/'.urlencode($tag).'" target="_blank" class="tag-word">'.$tag.'</a>';
      }
    }
    return $strtag;
}
function TagToLinkSearchMarketing($str,$type=5){
    if($type == 5){
        $arrtag = explode(',',trim($str));
        $strtag = '';
        $arrtag = array_filter($arrtag);
        foreach($arrtag as $tag){
            $strtag .= '<a href="/search/marketing-online.html?iMar=5&keyword='.urlencode($tag).'" target="_blank"><span class="tag-word" itemprop="keywords">'.$tag.'</span></a>';
        }
    }else {
        $arrtag = explode(',',trim($str));
        $strtag = '';
        $arrtag = array_filter($arrtag);
        foreach($arrtag as $tag){
            $strtag .= '<a href="/search/marketing-chien-luoc.html?iMar=6&keyword='.urlencode($tag).'" target="_blank"><span class="tag-word" itemprop="keywords">'.$tag.'</span></a>';
        }
    }
    return $strtag;
}

function updateVisit($iNew){
	$iNew	=	intval($iNew);
	//Update so luot visit
	$db_select	=	new db_query("SELECT nev_count
											FROM	news_visit
											WHERE	nev_new_id = " . $iNew);
	if($row = mysql_fetch_assoc($db_select->result)){
		$db_ex	=	new db_execute("UPDATE news_visit SET nev_count = nev_count + 1 WHERE nev_new_id = " . $iNew . " LIMIT 1");
		unset($db_ex);
	}else{
		$db_ex	=	new db_execute("INSERT INTO news_visit(nev_new_id,nev_count) VALUES(" . $iNew . ", 1)");
		unset($db_ex);
	}
	unset($db_select);
}
//Hàm xóa khoảng trắng ở đầu và cuối chuỗi và thay thế dấu space bằng dấu + (trong URL query string)
function replaceSpaceToPlus($str){
    //Hàm xóa khoảng trắng ở đầu và cuối chuỗi và thay thế dấu space bằng dấu + (trong URL query string)
    $str = trim($str);
    return str_replace(' ','+',$str);
}

?>

<?php
//Tach url dang segment thanh tung block nho, tra ve mang cac block
function explode_segments($url){
    $segments = array();
	foreach (explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $url)) as $val){
		if ($val != ''){
			$segments[] = $val;
		}
	}
    return $segments;
}

/**
 * Tao cache
 * 
 * @param $cache_id String
 * @param $cache_body String
 * @param $cache_expried int thoi han song cua cache
 */
function cache_set($cache_id, $cache_body, $cache_expried = 3600){
   $cache_id = trim($cache_id);
   if($cache_id != ""){
      $cache_id = md5($cache_id);
      $sqldel = 'DELETE FROM cache WHERE ca_id = \''.$cache_id.'\'';
      $dbex = new db_execute($sqldel);
      
      $sqlins = 'INSERT INTO cache (ca_id, ca_body, ca_created, ca_expried) VALUES(\''.$cache_id.'\', \''.$cache_body.'\', '.time().', '.(time() + $cache_expried).')';
      $dbex = new db_execute($sqlins);
      unset($dbex);
   }
}

/**
 * Lay cache
 * 
 * @param $cache_id String
 */
function cache_get($cache_id){
   $cache_id = md5(trim($cache_id));
   $cache = array(
      'cache_id' => $cache_id,
      'cache_body' => null,
   );
   
   $sql = "SELECT * FROM cache WHERE ca_id = '".$cache_id."'";
   $rel = new db_query($sql);
   $row = mysql_fetch_assoc($rel->result);
   unset($rel);
   if(!empty($row) && $row['ca_expried'] > time()){
      $cache['cache_body'] = $row['ca_body'];
   }
   return $cache;
}
?>